package com.xnfh.image

import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import java.io.File

/**
 * Glide实现的图片加载
 */
class GlideImageLoaderDisplayer : IImageLoaderDisplayer {
    /**
     * 加载apk资源文件图片
     */
    override fun loadResourceImg(context: Context?, resId: Int, imageView: ImageView?) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions()
            options.centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
            Glide.with(context!!)
                .load(resId)
                .apply(options)
                .into(imageView!!)
        }
    }

    /**
     * 加载本地文件图片
     */
    override fun loadLocalImg(
        context: Context?,
        file: String?,
        imageView: ImageView?,
        placeHolder: Int,
        errorHolder: Int
    ) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions.placeholderOf(placeHolder).error(errorHolder)
            options.centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
            Glide.with(context!!)
                .load(File(file))
                .apply(options)
                .into(imageView!!)
        }
    }

    /**
     * 加载网络图片
     */
    override fun loadNetImg(context: Context?, url: String?, imageView: ImageView?) {
        loadNetImg(
            context,
            url,
            imageView,
            R.drawable.shape_default_load_bg,
            R.drawable.shape_default_load_bg
        )
    }

    /**
     * 加载网络图片,有监听
     */
    override fun loadNetImg(context: Context?, url: String?, iImageLoadResult: IImageLoadResult?) {
        Glide.with(context!!)
            .load(url)
            .into(object : SimpleTarget<Drawable?>() {
                override fun onLoadFailed(errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    iImageLoadResult?.onLoadFailed()
                }

                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable?>?
                ) {
                    iImageLoadResult?.onResourceReady(resource)
                }
            })
    }

    /**
     * 加载网络图片(有默认图)
     */
    override fun loadNetImg(
        context: Context?,
        url: String?,
        imageView: ImageView?,
        placeHolder: Int,
        errorHolder: Int
    ) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions.placeholderOf(placeHolder).error(errorHolder)
            Glide.with(context!!)
                .load(url)
                .apply(options.centerCrop())
                .into(imageView!!)
        }
    }

    /**
     * 加载网络 圆角图片
     * @param dp 圆角弧度
     */
    override fun loadRoundCornerImg(
        context: Context?,
        url: String?,
        imageView: ImageView?,
        dp: Int
    ) {
        loadRoundCornerImg(
            context,
            url,
            imageView,
            R.drawable.shape_default_load_bg,
            R.drawable.shape_default_load_bg,
            dp
        )
    }

    /**
     * 加载本地 圆角图片
     * @param dp 圆角弧度
     */
    override fun loadRoundCornerImg(context: Context?, url: Int, imageView: ImageView?, dp: Int) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions()
            Glide.with(context!!)
                .load(url)
                .apply(options.transform(CenterCrop(), RoundedCorners(dp)))
                .into(imageView!!)
        }
    }

    /**
     * 加载网络 圆角图片（有默认图）
     * @param dp 圆角弧度
     */
    override fun loadRoundCornerImg(
        context: Context?,
        url: String?,
        imageView: ImageView?,
        placeHolder: Int,
        errorHolder: Int,
        dp: Int
    ) {
        if (ImageHelper.isValidConntext(context)) {
            val glideUrl = GlideUrl(
                url, LazyHeaders.Builder()
                    .addHeader(
                        "User-Agent",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36(KHTML, like Gecko) Chrome 47.0.2526.106 Safari/537.36"
                    )
                    .build()
            )
            val options = RequestOptions.placeholderOf(placeHolder).error(errorHolder)
            Glide.with(context!!)
                .load(glideUrl)
                .apply(options.transform(CenterCrop(), RoundedCorners(dp)))
                .into(imageView!!)
        }
    }

    override fun loadRoundCornerImg(
        context: Context?,
        url: String?,
        imageView: ImageView?,
        placeHolder: Int,
        errorHolder: Int,
        leftTopRadius: Int,
        rightTopRadius: Int,
        leftBottomRadius: Int,
        rightBottomRadius: Int
    ) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions.placeholderOf(placeHolder).error(errorHolder)
            Glide.with(context!!)
                .load(url)
                .apply(
                    options.transform(
                        CenterCrop(),
                        RoundBitmapTransformation(
                            leftTopRadius,
                            rightTopRadius,
                            leftBottomRadius,
                            rightBottomRadius
                        )
                    )
                )
                .into(imageView!!)
        }
    }

    /**
     * 加载webp本地图片
     */
    override fun loadWebPRoundCornerImg(
        context: Context?,
        url: Int,
        imageView: ImageView?,
        isLoop: Boolean
    ) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions()
            Glide.with(context!!)
                .load(url)
                .addListener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        if (resource is WebpDrawable) {
                            if(isLoop){
                                resource.loopCount = -1
                            }
                        }
                        return false
                    }
                })
                .into(imageView!!)
        }
    }
    override fun loadWebPRoundCornerImg(
        context: Context?,
        url: String,
        imageView: ImageView?,
        isLoop: Boolean
    ) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions.placeholderOf(R.drawable.shape_default_load_bg).error(
                R.drawable.shape_default_load_bg
            )
            Glide.with(context!!)
                .load(url)
                .addListener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        return false
                    }

                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        if (resource is WebpDrawable) {
                            if(isLoop){
                                resource.loopCount = -1
                            }
                        }
                        return false
                    }
                })
                .into(imageView!!)
        }
    }

    /**
     * 加载网络 圆形图片
     */
    override fun loadCircleImage(context: Context?, url: String?, imageView: ImageView?) {
        loadCircleImage(
            context,
            url,
            imageView,
            R.drawable.shape_default_load_bg,
            R.drawable.shape_default_load_bg
        )
    }

    /**
     * 加载本地 圆形图片
     */
    override fun loadCircleImage(context: Context?, url: Int, imageView: ImageView?) {
        loadCircleImage(
            context,
            url,
            imageView,
            R.drawable.shape_default_load_bg,
            R.drawable.shape_default_load_bg
        )
    }

    /**
     * 加载网络 圆形图片（有默认图）
     */
    override fun loadCircleImage(
        context: Context?,
        url: String?,
        imageView: ImageView?,
        placeholder: Int,
        errorholder: Int
    ) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions.placeholderOf(placeholder).error(errorholder)
            Glide.with(context!!)
                .load(url)
                .apply(options.circleCrop())
                .into(imageView!!)
        }
    }

    /**
     * 加载本地 圆形图片（有默认图）
     */
    override fun loadCircleImage(
        context: Context?,
        layoutId: Int,
        imageView: ImageView?,
        placeholder: Int,
        errorholder: Int
    ) {
        if (ImageHelper.isValidConntext(context)) {
            val options = RequestOptions.placeholderOf(placeholder).error(errorholder)
            options.fitCenter()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
            Glide.with(context!!)
                .load(layoutId)
                .apply(options)
                .into(imageView!!)
        }
    }
}